#include <bits/stdc++.h>
using namespace std;

const int N = 1e4;
class Solution
{
  public:
    vector<vector<int>> mem;
    int maxLenth = 0;
    int end = 0;
    int dfs(string &s1, string &s2, int i, int j)
    {
        if (i == 0 || j == 0)
            return 0;
        if (mem[i][j] != -1)
            return mem[i][j];
        if (s1[i - 1] == s2[j - 1])
            mem[i][j] = dfs(s1, s2, i - 1, j - 1) + 1;
        else
            mem[i][j] = 0;
        return mem[i][j];
    }
    string LCS(string str1, string str2)
    {

        int n = str1.size();
        int m = str2.size();
        mem = vector<vector<int>>(n + 1, vector<int>(m + 1, -1));
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                int len = dfs(str1, str2, i, j);
                if (len > maxLenth)
                {
                    maxLenth = len;
                    end = i;
                }
            }
        }
        return maxLenth ? str1.substr(end - maxLenth, maxLenth) : "-1";
    }
};

class Solution
{
  public:
    string LCS(string str1, string str2)
    {
        int end_pos = 0;
        int maxlen = 0;
        int n = str1.size();
        int m = str2.size();
        vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                if (str1[i - 1] == str2[j - 1])
                {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (dp[i][j] > maxlen)
                    {
                        maxlen = dp[i][j];
                        end_pos = i;
                    }
                }
                else
                {
                    dp[i][j] = 0;
                }
            }
        }
        return maxlen ? str1.substr(end_pos - maxlen, maxlen) : "-1";
    }
};